package com.tim.app.ui.activity.person_center;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.callback.LoginCallBack;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.PrepareExchangeBean;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.dialog.TipDialog;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.UMLoginUtil;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by wdy on 2017/8/22.
 */

public class MyIncomeActivity extends BaseActivity {
    private ImageButton ibBack;
    private RelativeLayout rl_income_detail;
    private TextView mTv_num_moli;
    private TextView mTv_mun_money;
    private Button mBtn_exchange;
    private Button mBtn_money;
    private RelativeLayout mRl_income_detail;
    private RelativeLayout mRl_common_question;
    private RelativeLayout mRl_do_task;
    private static final int CODE = 0x111;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_myincome;
    }

    @Override
    public void initView() {
        ibBack = (ImageButton) findViewById(R.id.ibBack);
        rl_income_detail = (RelativeLayout) findViewById(R.id.rl_income_detail);
        mTv_num_moli = (TextView) findViewById(R.id.tv_num_moli);
        mTv_mun_money = (TextView) findViewById(R.id.tv_mun_money);
        mBtn_exchange = (Button) findViewById(R.id.btn_exchange);
        mBtn_money = (Button) findViewById(R.id.btn_money);
        mRl_income_detail = (RelativeLayout) findViewById(R.id.rl_income_detail);
        mRl_common_question = (RelativeLayout) findViewById(R.id.rl_common_question);
        mRl_do_task = (RelativeLayout) findViewById(R.id.rl_do_task);
    }

    @Override
    public void initData() {
        mRl_common_question.setOnClickListener(this);
        mBtn_exchange.setOnClickListener(this);
        ibBack.setOnClickListener(this);
        rl_income_detail.setOnClickListener(this);
        mBtn_money.setOnClickListener(this);
        prepareDate();
        EventManager.ins().registListener(EventTag.FLOWER_NUM_CHANGE, eventListener);
    }

    private com.application.library.runtime.event.EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            if (what == EventTag.FLOWER_NUM_CHANGE) {
                mTv_num_moli.setText(date.getMoliFlowerCount() - arg1 + "");
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.FLOWER_NUM_CHANGE, eventListener);
    }

    public void prepareDate() {
        showLoadingDialog();
        API_User.ins().prepareExchange(TAG, UserManager.ins().getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                hideLoadingDialog();
                Log.e("tag", "resultValue====" + resultValue);
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    PrepareExchangeBean prepareExchangeBean = new Gson().fromJson(resultValue, PrepareExchangeBean.class);
                    setDate(prepareExchangeBean.getRes().getConfigureflowermoney());
                }
                return false;
            }
        });
    }

    private PrepareExchangeBean.ResBean.ConfigureflowermoneyBean date;

    private void setDate(PrepareExchangeBean.ResBean.ConfigureflowermoneyBean date) {
        this.date = date;
        mTv_num_moli.setText(date.getMoliFlowerCount() + "");
        mTv_mun_money.setText(date.getMoneyCount() + "");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack:
                finish();
                break;
            case R.id.rl_income_detail:
                startActivity(new Intent(MyIncomeActivity.this, IncomeDetailActivity.class));
                break;
            case R.id.btn_money:
                goToExchangeMoney();
                break;
            case R.id.btn_exchange:
                Intent intent = new Intent(this, ExchangeMoneyActivity.class);
                intent.putExtra("date", date);
                //  startActivityForResult(intent, CODE);
                startActivity(intent);
                break;
            case R.id.rl_common_question:
                startActivity(new Intent(this, HelpCenterActivity.class));
                break;
        }
    }


    private void goToExchangeMoney() {
        if (TextUtils.isEmpty(UserManager.ins().getLoginUser().getPlatformWxUid())) {
            final UMLoginUtil loginUtil = new UMLoginUtil(this);
            final TipDialog tipDialog = new TipDialog(MyIncomeActivity.this);
            tipDialog.setTextDes("申请提现，需先绑定微信");
            tipDialog.setButton1("去绑定", new TipDialog.DialogButtonOnClickListener() {
                @Override
                public void onClick(View button, TipDialog dialog) {
                    tipDialog.dismiss();
                    wxLogin(loginUtil);
                }
            });
            tipDialog.setButton2("取消", new TipDialog.DialogButtonOnClickListener() {
                @Override
                public void onClick(View button, TipDialog dialog) {
                    tipDialog.dismiss();
                }
            });
            tipDialog.show();
        } else {
            Intent intent = new Intent(MyIncomeActivity.this, ToWxMoneyActivity.class);
            intent.putExtra("date", MyIncomeActivity.this.date);
            startActivity(intent);
        }
    }

    private void wxLogin(UMLoginUtil loginUtil) {
        loginUtil.login(SHARE_MEDIA.WEIXIN, new LoginCallBack() {
            @Override
            public void onFailed(String msg) {
                ToastUtil.showToast(RT.getString(R.string.error_login_wx));
            }

            @Override
            public void onSuccess(String unionid, String name, String avatar, String token) {
                Log.e("tag", "onSuccess=========" + unionid);
                bindWx("4", unionid, token);
            }
        });
    }

    private void bindWx(String platformType, String platformUid, String accessToken) {


        API_User.ins().bindWx(TAG, platformType, UserManager.ins().getUserId(), platformUid, accessToken, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                //  Log.e("tag", "resultValue=====" + resultValue + "===errCode====" + errCode);
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    final TipDialog tipDialog = new TipDialog(MyIncomeActivity.this);
                    tipDialog.setTextDes("绑定成功");
                    tipDialog.setButton1("确定", new TipDialog.DialogButtonOnClickListener() {
                        @Override
                        public void onClick(View button, TipDialog dialog) {
                            tipDialog.dismiss();
                            UserManager.ins().getLoginUser().setPlatformWxUid("111");
                            Intent intent = new Intent(MyIncomeActivity.this, ToWxMoneyActivity.class);
                            intent.putExtra("date", MyIncomeActivity.this.date);
                            startActivity(intent);
                        }
                    });
                    tipDialog.setCancleGone();
                    tipDialog.show();

                } else if (errCode == ResponseResult.ResultStatus.DONE) {
//                    Intent intent = new Intent(MyIncomeActivity.this, ToWxMoneyActivity.class);
//                    intent.putExtra("date", MyIncomeActivity.this.date);
//                    startActivity(intent);
                    try {
                        JSONObject jsonObject = new JSONObject(resultValue);
                        ToastUtil.showToast(jsonObject.getString("message"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else {
                    ToastUtil.showToast("绑定失败");
                }
                return false;
            }
        });
    }
}
